package pa1.sockets;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;

public class ServerThread extends Thread{

	private String clientName;
	private int eventNumber = 0;
	
	private BufferedReader in;
	private PrintWriter out;
	private Socket connectionSocket;
	private Logger log;
	
	
	public ServerThread(Socket connectionSocket, Logger log){
		this.connectionSocket = connectionSocket;
		this.log = log;
		try {
			//open input and output streams in order to be able to receive and send data from
			//the socket connection
			in = new BufferedReader(new InputStreamReader(this.connectionSocket.getInputStream()));
			out = new PrintWriter(connectionSocket.getOutputStream(), true);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	@Override
	public void run() {
		String input;
		try {
			//handle input
			while((input = in.readLine()) != null){					
				//get command
				String cmd[] = input.split(" ");
				if(cmd[0].equalsIgnoreCase("HELO")){
					this.clientName = cmd[1];
					sendResponse("OK");
				}
				else if(cmd[0].equalsIgnoreCase("NREV")){
					sendResponse("OK");
				}
				else if(cmd[0].equalsIgnoreCase("EVNT")){
					String eventDescription = input.substring(5);
					log.logEvent(this.eventNumber, this.clientName, eventDescription);	
					this.eventNumber++;
				}
				else if(cmd[0].equalsIgnoreCase("QUIT")){
					sendResponse("BYEE");
				}					
			}
		} catch (IOException e1) {
			e1.printStackTrace();
		}
		try {
			this.in.close();
			this.out.close();
			this.connectionSocket.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
		
	}
	
	//this function is used to send response messages to the client
	public void sendResponse(String response){
		this.out.println(response);
	}
	


}
